package com.fangxing.configs.shiro;

import com.fangxing.module.user.dao.AccountRepository;
import com.fangxing.module.user.entity.AccountEntity;
import com.fangxing.module.user.service.AccountService;
import com.fangxing.util.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    AccountService accountService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String)token.getPrincipal();
        String pwd = (String)token.getCredentials();

        AccountEntity accountEntity = accountService.checkAccount(username, pwd);
        if (accountEntity == null) {
            return null;
        }

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                accountEntity, //用户名
                accountEntity.getPassword(), //密码
                ByteSource.Util.bytes(accountEntity.getSalt()),//salt=username+salt
                accountEntity.getUsername()  //realm name
        );

        return authenticationInfo;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }


}
